package com.easemob.chat;

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Process;
import android.text.TextUtils;
import com.easemob.EMCallBack;
import com.easemob.EMConnectionListener;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent.Event;
import com.easemob.b.a;
import com.easemob.chat.core.XmppConnectionManager;
import com.easemob.chat.core.e;
import com.easemob.chat.core.f;
import com.easemob.chat.core.k;
import com.easemob.chat.core.l;
import com.easemob.cloud.HttpClientConfig;
import com.easemob.cloud.HttpClientManager;
import com.easemob.exceptions.EMExceptionUtils;
import com.easemob.exceptions.EMNetworkUnconnectedException;
import com.easemob.exceptions.EMNoActiveCallException;
import com.easemob.exceptions.EMServiceNotReadyException;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.CryptoUtils;
import com.easemob.util.EMLog;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message.Type;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.json.JSONObject;

public class EMChatManager
{
  private static final String TAG = "chat";
  private static final String NEW_MSG_BROADCAST = "easemob.newmsg.";
  private static final String READ_ACK_MSG_BROADCAST = "easemob.ackmsg.";
  private static final String DELIVERY_ACK_MSG_BROADCAST = "easemob.deliverymsg.";
  private static final String CONTACT_INVITE_EVENT_BROADCAST = "easemob.contact.invite.";
  private static final String OFFLINE_MSG_BROADCAST = "easemob.offlinemsg.";
  private static final String INCOMING_VOICE_CALL_BROADCAST = "easemob.incomingvoicecall.invite";
  private static final String INCOMING_CALL_BROADCAST = "easemob.incomingcall.invite";
  private static final String CMD_MSG_BROADCAST = "easemob.cmdmsg";
  private static EMChatManager instance = new EMChatManager();
  private ChatManager xmppChatManager;
  private XmppConnectionManager xmppConnectionManager;
  private EMChatManagerListener chatManagerListener = new EMChatManagerListener(null);
  private final ChatListener chatListener = new ChatListener(this);
  private final GroupChatListener groupChatListener = new GroupChatListener(this);
  private final RecvAckListener recvAckListener = new RecvAckListener();
  private Map<String, Chat> chats = new HashMap();
  private final List<ConnectionListener> connectionListeners = Collections.synchronizedList(new ArrayList());
  private List<EMConnectionListener> newConnectionListeners = Collections.synchronizedList(new ArrayList());
  private Handler handler = new Handler();
  private final XmppConnectionListener xmppConnectionListener = new XmppConnectionListener(null);
  private Context applicationContext;
  private EMNotifier notifier;
  private CryptoUtils cryptoUtils = new CryptoUtils();
  private EncryptProvider encryptProvider = null;
  private ExecutorService threadPool = null;
  private EMChatOptions chatOptions;
  private ArrayList<Presence> offlineRosterPresenceList = new ArrayList();
  ArrayList<EMMessage> offlineMessagesList = new ArrayList();
  ArrayList<EMMessage> offlineCmdMessagesList = new ArrayList();
  ExecutorService msgCountThreadPool;
  boolean stopService;

  public void login(String paramString1, String paramString2, final EMCallBack paramEMCallBack)
  {
    if (!EMChat.getInstance().isSDKInited())
      throw new RuntimeException("SDK is not initialized!");
    if (paramEMCallBack == null)
      throw new IllegalArgumentException("callback is null!");
    if ((paramString1 == null) || (paramString2 == null) || (paramString1.equals("")) || (paramString2.equals("")))
      throw new IllegalArgumentException("username or password is null or empty!");
    EMLog.e("chat", "emchat manager login in process:" + Process.myPid());
    paramString1 = paramString1.toLowerCase();
    EMSessionManager.getInstance().login(paramString1, paramString2, true, new EMCallBack()
    {
      public void onSuccess()
      {
        EMChatManager.this.doStartService();
        paramEMCallBack.onSuccess();
      }

      public void onProgress(int paramAnonymousInt, String paramAnonymousString)
      {
      }

      public void onError(int paramAnonymousInt, String paramAnonymousString)
      {
        f.a().i();
        EMChatManager.this.doStopService();
        paramEMCallBack.onError(paramAnonymousInt, paramAnonymousString);
      }
    });
  }

  public void logout()
  {
    EMSessionManager.getInstance().clearLastLoginUser();
    EMSessionManager.getInstance().clearLastLoginPwd();
    try
    {
      EMContactManager.getInstance().reset();
      this.groupChatListener.clearRecentMsgIdQueue();
      this.chatListener.clearRecentMsgIdQueue();
      this.chatListener.resetOfflineFlags();
      this.groupChatListener.resetOfflineFlags();
      this.chats.clear();
      EMConversationManager.getInstance().clear();
      EMMessageHandler.getInstance().onDestroy();
    }
    catch (Exception localException1)
    {
      localException1.printStackTrace();
    }
    EMGroupManager.getInstance().logout();
    try
    {
      if (e.a() != null)
        e.a().b();
    }
    catch (Exception localException2)
    {
      localException2.printStackTrace();
    }
    try
    {
      EMSessionManager.getInstance().syncLogout();
    }
    catch (Exception localException3)
    {
      localException3.printStackTrace();
    }
    f.a().i();
    EMChat.getInstance().appInited = false;
    if (EMChatConfig.isDebugTrafficMode())
      a.c();
    doStopService();
  }

  public void logout(final EMCallBack paramEMCallBack)
  {
    Thread local2 = new Thread()
    {
      public void run()
      {
        if (paramEMCallBack != null)
          paramEMCallBack.onProgress(0, null);
        EMChatManager.this.logout();
        if (paramEMCallBack != null)
          paramEMCallBack.onSuccess();
      }
    };
    local2.setPriority(9);
    local2.start();
  }

  void changePasswordOnServer(String paramString)
    throws EaseMobException
  {
    EMSessionManager.getInstance().changePasswordXMPP(paramString);
  }

  public void createAccountOnServer(String paramString1, String paramString2)
    throws EaseMobException
  {
    paramString1 = paramString1.toLowerCase();
    Pattern localPattern = Pattern.compile("^[a-zA-Z0-9_-]{1,}$");
    boolean bool = localPattern.matcher(paramString1).find();
    if (!bool)
      throw new EaseMobException("用户名不合法");
    EMSessionManager.getInstance().createAccountRest(paramString1, paramString2);
  }

  public boolean isConnected()
  {
    return EMSessionManager.getInstance().isConnected();
  }

  public void registerEventListener(EMEventListener paramEMEventListener)
  {
    EMNotifier.getInstance(this.applicationContext).registerEventListener(paramEMEventListener);
  }

  public void registerEventListener(EMEventListener paramEMEventListener, EMNotifierEvent.Event[] paramArrayOfEvent)
  {
    EMNotifier.getInstance(this.applicationContext).registerEventListener(paramEMEventListener, paramArrayOfEvent);
  }

  public void unregisterEventListener(EMEventListener paramEMEventListener)
  {
    EMNotifier.getInstance(this.applicationContext).removeEventListener(paramEMEventListener);
  }

  private EMChatManager()
  {
    this.cryptoUtils.init(1);
    this.threadPool = Executors.newCachedThreadPool();
    this.msgCountThreadPool = Executors.newSingleThreadExecutor();
    this.chatOptions = new EMChatOptions();
    new ChatServiceConnection(null);
  }

  public static synchronized EMChatManager getInstance()
  {
    if (instance.applicationContext == null)
      instance.applicationContext = EMChat.getInstance().getAppContext();
    return instance;
  }

  synchronized EMChatManager onInit()
  {
    EMLog.d("chat", "init chat manager");
    if (this.applicationContext == null)
      this.applicationContext = EMChat.getInstance().getAppContext();
    this.notifier = EMNotifier.getInstance(this.applicationContext);
    return this;
  }

  void onNewConnectionCreated(XmppConnectionManager paramXmppConnectionManager)
  {
    EMLog.d("chat", "on new connection created");
    init(paramXmppConnectionManager);
    EMGroupManager.getInstance().init(paramXmppConnectionManager);
    addPacketListeners(paramXmppConnectionManager.getConnection());
    if (EMContactManager.getInstance().enableRosterVersion)
    {
      EMLog.d("chat", "enable roster version. set roster storage");
      paramXmppConnectionManager.getConnection().setRosterStorage(EMContactManager.getInstance().getRosterStorage(this.applicationContext));
      EMContactManager.getInstance().loadContacts();
    }
    doStartService();
  }

  void onAppInited()
  {
    try
    {
      processOfflinePresenceMessages();
      EMGroupManager.getInstance().processOfflineMessages();
      processOfflineMessages();
      processOfflineCmdMessages();
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
  }

  private void addPacketListeners(XMPPConnection paramXMPPConnection)
  {
    if ((paramXMPPConnection.isConnected()) && (paramXMPPConnection.isAuthenticated()))
      return;
    MessageTypeFilter localMessageTypeFilter1 = new MessageTypeFilter(Message.Type.chat);
    paramXMPPConnection.addPacketListener(this.chatListener, localMessageTypeFilter1);
    MessageTypeFilter localMessageTypeFilter2 = new MessageTypeFilter(Message.Type.groupchat);
    paramXMPPConnection.addPacketListener(this.groupChatListener, localMessageTypeFilter2);
    MessageTypeFilter localMessageTypeFilter3 = new MessageTypeFilter(Message.Type.normal);
    paramXMPPConnection.addPacketListener(this.recvAckListener, localMessageTypeFilter3);
    PacketTypeFilter local3 = new PacketTypeFilter(Presence.class)
    {
      public boolean accept(Packet paramAnonymousPacket)
      {
        if ((paramAnonymousPacket instanceof Presence))
        {
          Presence localPresence = (Presence)paramAnonymousPacket;
          if ((localPresence.getType().equals(Presence.Type.subscribed)) || (localPresence.getType().equals(Presence.Type.subscribe)) || (localPresence.getType().equals(Presence.Type.unsubscribed)) || (localPresence.getType().equals(Presence.Type.unsubscribe)))
            return true;
        }
        return false;
      }
    };
    this.xmppConnectionManager.getConnection().addPacketListener(new SingleInvitationListener(null), local3);
  }

  private void init(XmppConnectionManager paramXmppConnectionManager)
  {
    EMLog.d("chat", "init chat manager");
    if ((paramXmppConnectionManager == null) || (paramXmppConnectionManager.getConnection() == null))
    {
      EMLog.e("chat", "error in Chat Manage init. connection is null");
      return;
    }
    try
    {
      this.xmppConnectionManager = paramXmppConnectionManager;
      this.xmppChatManager = paramXmppConnectionManager.getConnection().getChatManager();
      this.xmppChatManager.addChatListener(this.chatManagerListener);
      EMMessageHandler.getInstance().onInit();
      paramXmppConnectionManager.setChatConnectionListener(this.xmppConnectionListener);
      try
      {
        if (Class.forName("com.easemob.chat.EMVoiceCallManager") != null)
          EMVoiceCallManager.getInstance().init();
      }
      catch (Throwable localThrowable)
      {
      }
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
  }

  void processOfflinePresenceMessages()
  {
    EMLog.d("chat", "process offline RosterPresence msg start");
    Iterator localIterator = this.offlineRosterPresenceList.iterator();
    while (localIterator.hasNext())
    {
      Presence localPresence = (Presence)localIterator.next();
      processRosterPresence(localPresence);
    }
    this.offlineRosterPresenceList.clear();
    EMLog.d("chat", "proess offline RosterPresence msg finish");
  }

  void processOfflineCmdMessages()
  {
    Iterator localIterator = this.offlineCmdMessagesList.iterator();
    while (localIterator.hasNext())
    {
      EMMessage localEMMessage = (EMMessage)localIterator.next();
      this.chatListener.sendCmdMsgBroadcast(localEMMessage);
    }
    this.offlineCmdMessagesList.clear();
  }

  void processOfflineMessages()
  {
    this.chatListener.sendOfflineMsgBroadcast();
    this.groupChatListener.sendOfflineMsgBroadcast();
  }

  private void processRosterPresence(Presence paramPresence)
  {
    EMPresenceHandler.getInstance().processRosterPresence(paramPresence);
  }

  private void acceptInvitation(String paramString, boolean paramBoolean)
    throws EaseMobException
  {
    EMPresenceHandler.getInstance().acceptInvitation(paramString, paramBoolean);
  }

  public void acceptInvitation(String paramString)
    throws EaseMobException
  {
    acceptInvitation(EMContactManager.getEidFromUserName(paramString), true);
  }

  public void refuseInvitation(String paramString)
    throws EaseMobException
  {
    EMPresenceHandler.getInstance().refuseInvitation(paramString);
  }

  public void sendMessage(EMMessage paramEMMessage)
    throws EaseMobException
  {
    sendMessage(paramEMMessage, null);
  }

  public void sendMessage(EMMessage paramEMMessage, EMCallBack paramEMCallBack)
  {
    if (this.xmppConnectionManager == null)
    {
      EMMessageUtils.asyncCallback(paramEMCallBack, -1022, "connection init is failed due to failed login");
      return;
    }
    int i = EMMessageUtils.checkMessageError(paramEMMessage);
    Object localObject;
    if (i != 0)
    {
      paramEMMessage.status = EMMessage.Status.FAIL;
      localObject = new ContentValues();
      ((ContentValues)localObject).put("status", paramEMMessage.status.ordinal());
      e.a().a(paramEMMessage.msgId, (ContentValues)localObject);
      if (paramEMCallBack != null)
        EMMessageUtils.asyncCallback(paramEMCallBack, i, "send message error");
    }
    else
    {
      if (paramEMMessage.getChatType() == EMMessage.ChatType.GroupChat)
      {
        sendGroupMessage(paramEMMessage, paramEMCallBack);
        return;
      }
      localObject = paramEMMessage.to.eid;
      if (!((String)localObject).contains("@"))
      {
        EMChatConfig.getInstance();
        localObject = localObject + "@" + EMChatConfig.DOMAIN;
      }
      Chat localChat = (Chat)this.chats.get(localObject);
      if (localChat == null)
      {
        EMLog.d("chat", "create a new chat for jid:" + (String)localObject);
        localChat = this.xmppChatManager.createChat((String)localObject, null);
      }
      EMMessageHandler.getInstance().sendMessage(localChat, paramEMMessage, paramEMCallBack);
    }
  }

  public void sendGroupMessage(EMMessage paramEMMessage, EMCallBack paramEMCallBack)
  {
    EMMessageHandler.getInstance().sendGroupMessage(paramEMMessage, paramEMCallBack);
  }

  void notifyMessage(EMMessage paramEMMessage)
  {
    this.notifier.notifyChatMsg(paramEMMessage);
  }

  void broadcastMessage(EMMessage paramEMMessage)
  {
    EMLog.d("chat", "broad offline msg");
    this.notifier.sendBroadcast(paramEMMessage);
  }

  void notifiyReadAckMessage(String paramString1, String paramString2)
  {
    this.notifier.sendReadAckMsgBroadcast(paramString1, paramString2);
  }

  void notifyDeliveryAckMessage(String paramString1, String paramString2)
  {
    this.notifier.sendDeliveryAckMsgBroadcast(paramString1, paramString2);
  }

  void notifyIncomingCall(String paramString1, String paramString2)
  {
    this.notifier.sendIncomingVoiceCallBroadcast(paramString1, paramString2);
  }

  public String getNewMessageBroadcastAction()
  {
    return "easemob.newmsg." + getBroadcastSuffix();
  }

  public String getCmdMessageBroadcastAction()
  {
    return "easemob.cmdmsg" + getBroadcastSuffix();
  }

  public String getAckMessageBroadcastAction()
  {
    return "easemob.ackmsg." + getBroadcastSuffix();
  }

  public String getDeliveryAckMessageBroadcastAction()
  {
    return "easemob.deliverymsg." + getBroadcastSuffix();
  }

  public String getContactInviteEventBroadcastAction()
  {
    return "easemob.contact.invite." + getBroadcastSuffix();
  }

  public String getOfflineMessageBroadcastAction()
  {
    return "easemob.offlinemsg." + getBroadcastSuffix();
  }

  public String getIncomingVoiceCallBroadcastAction()
  {
    return "easemob.incomingvoicecall.invite" + getBroadcastSuffix();
  }

  public String getIncomingCallBroadcastAction()
  {
    return "easemob.incomingcall.invite" + getBroadcastSuffix();
  }

  private String getBroadcastSuffix()
  {
    if (this.applicationContext != null)
      return EMChatConfig.getInstance().APPKEY.replaceAll("#", ".").replaceAll("-", ".") + this.applicationContext.getPackageName();
    return EMChatConfig.getInstance().APPKEY.replaceAll("#", ".").replaceAll("-", ".");
  }

  public void ackMessageRead(String paramString1, String paramString2)
    throws EaseMobException
  {
    if (!this.chatOptions.getRequireAck())
    {
      EMLog.d("chat", "chat option reqire ack set to false. skip send out ask msg read");
      return;
    }
    checkConnection();
    String str = EMContactManager.getEidFromUserName(paramString1);
    Chat localChat = (Chat)this.chats.get(str);
    if (localChat == null)
    {
      localChat = this.xmppChatManager.createChat(str, null);
      this.chats.put(str, localChat);
    }
    EMMessageHandler.getInstance().ackMessageRead(getCurrentUser(), paramString1, paramString2);
  }

  public void setMessageListened(EMMessage paramEMMessage)
  {
    paramEMMessage.setListened(true);
    e.a().g(paramEMMessage.getMsgId(), true);
  }

  void checkConnection()
    throws EaseMobException
  {
    EMSessionManager.getInstance().checkConnection();
  }

  public void addConnectionListener(final ConnectionListener paramConnectionListener)
  {
    if (paramConnectionListener != null)
    {
      this.connectionListeners.add(paramConnectionListener);
      if ((this.xmppConnectionManager != null) && (this.xmppConnectionManager.getConnection() != null) && (this.xmppConnectionManager.getConnection().isConnected()))
        this.handler.post(new Runnable()
        {
          public void run()
          {
            Iterator localIterator = EMChatManager.this.connectionListeners.iterator();
            while (localIterator.hasNext())
            {
              ConnectionListener localConnectionListener = (ConnectionListener)localIterator.next();
              if ((localConnectionListener != null) && (localConnectionListener.equals(paramConnectionListener)))
                localConnectionListener.onConnected();
            }
          }
        });
      else
        this.handler.post(new Runnable()
        {
          public void run()
          {
            Iterator localIterator = EMChatManager.this.connectionListeners.iterator();
            while (localIterator.hasNext())
            {
              ConnectionListener localConnectionListener = (ConnectionListener)localIterator.next();
              if ((localConnectionListener != null) && (localConnectionListener.equals(paramConnectionListener)))
                localConnectionListener.onDisConnected("connection is disconnected");
            }
          }
        });
    }
  }

  public void addConnectionListener(final EMConnectionListener paramEMConnectionListener)
  {
    if (paramEMConnectionListener == null)
      return;
    if (this.connectionListeners.contains(paramEMConnectionListener))
      return;
    this.newConnectionListeners.add(paramEMConnectionListener);
    if ((this.xmppConnectionManager != null) && (this.xmppConnectionManager.isConnected()))
      this.threadPool.submit(new Runnable()
      {
        public void run()
        {
          paramEMConnectionListener.onConnected();
        }
      });
    else
      this.threadPool.submit(new Runnable()
      {
        public void run()
        {
          paramEMConnectionListener.onDisconnected(-1001);
        }
      });
  }

  public void removeConnectionListener(ConnectionListener paramConnectionListener)
  {
    if (paramConnectionListener != null)
      this.connectionListeners.remove(paramConnectionListener);
  }

  public void removeConnectionListener(EMConnectionListener paramEMConnectionListener)
  {
    if (paramEMConnectionListener != null)
      this.newConnectionListeners.remove(paramEMConnectionListener);
  }

  public EMMessage getMessage(String paramString)
  {
    return EMConversationManager.getInstance().getMessage(paramString);
  }

  void replaceMessageId(String paramString1, String paramString2)
  {
    EMConversationManager.getInstance().replaceMessageId(paramString1, paramString2);
  }

  void addMessage(EMMessage paramEMMessage)
  {
    EMConversationManager.getInstance().addMessage(paramEMMessage);
  }

  void addMessage(EMMessage paramEMMessage, boolean paramBoolean)
  {
    EMConversationManager.getInstance().addMessage(paramEMMessage, paramBoolean);
  }

  public EMConversation getConversation(String paramString)
  {
    EMGroup localEMGroup = EMGroupManager.getInstance().getGroup(paramString);
    if (localEMGroup != null)
      return EMConversationManager.getInstance().getConversation(paramString, true);
    return EMConversationManager.getInstance().getConversation(paramString, false);
  }

  public EMConversation getConversation(String paramString, boolean paramBoolean)
  {
    return EMConversationManager.getInstance().getConversation(paramString, paramBoolean);
  }

  public boolean deleteConversation(String paramString)
  {
    return EMConversationManager.getInstance().deleteConversation(paramString);
  }

  public void deleteAllConversation()
  {
    EMConversationManager.getInstance().deleteAllConversations();
  }

  public void resetAllUnreadMsgCount()
  {
    EMConversationManager.getInstance().resetAllUnreadMsgCount();
  }

  public boolean deleteConversation(String paramString, boolean paramBoolean)
  {
    return EMConversationManager.getInstance().deleteConversation(paramString, paramBoolean);
  }

  public boolean deleteConversation(String paramString, boolean paramBoolean1, boolean paramBoolean2)
  {
    return EMConversationManager.getInstance().deleteConversation(paramString, paramBoolean1, paramBoolean2);
  }

  public boolean clearConversation(String paramString)
  {
    return EMConversationManager.getInstance().clearConversation(paramString);
  }

  public void loadAllConversations(EMCallBack paramEMCallBack)
  {
    EMConversationManager.getInstance().asyncloadAllConversations(paramEMCallBack, this.chatOptions.getNumberOfMessagesLoaded());
  }

  public void asyncLoadAllConversations(EMCallBack paramEMCallBack)
  {
    asyncLoadAllConversations(paramEMCallBack, this.chatOptions.getNumberOfMessagesLoaded());
  }

  void asyncLoadAllConversations(EMCallBack paramEMCallBack, int paramInt)
  {
    EMConversationManager.getInstance().asyncloadAllConversations(paramEMCallBack, paramInt);
  }

  public void loadAllConversations()
  {
    EMConversationManager.getInstance().loadAllConversations(this.chatOptions.getNumberOfMessagesLoaded());
  }

  public Hashtable<String, EMConversation> getAllConversations()
  {
    return EMConversationManager.getInstance().getAllConversations();
  }

  public int getUnreadMsgsCount()
  {
    return EMConversationManager.getInstance().getUnreadMsgsCount();
  }

  public void activityResumed()
  {
    if (this.notifier != null)
    {
      this.notifier.resetNotificationCount();
      this.notifier.cancelNotificaton();
    }
  }

  public void saveMessage(EMMessage paramEMMessage)
  {
    EMConversationManager.getInstance().saveMessage(paramEMMessage);
  }

  public void saveMessage(EMMessage paramEMMessage, boolean paramBoolean)
  {
    EMConversationManager.getInstance().saveMessage(paramEMMessage, paramBoolean);
  }

  public boolean updateMessageBody(EMMessage paramEMMessage)
  {
    return e.a().b(paramEMMessage);
  }

  public List<String> getContactUserNames()
    throws EaseMobException
  {
    return EMContactManager.getInstance().getRosterUserNames();
  }

  public String getCurrentUser()
  {
    return EMSessionManager.getInstance().currentUser.username;
  }

  public EMChatOptions getChatOptions()
  {
    return this.chatOptions;
  }

  public void setChatOptions(EMChatOptions paramEMChatOptions)
  {
    this.chatOptions = paramEMChatOptions;
  }

  public void setEncryptProvider(EncryptProvider paramEncryptProvider)
  {
    this.encryptProvider = paramEncryptProvider;
  }

  public EncryptProvider getEncryptProvider()
  {
    if (this.encryptProvider == null)
    {
      EMLog.d("chat", "encrypt provider is not set, create default");
      this.encryptProvider = new EncryptProvider()
      {
        public byte[] encrypt(byte[] paramAnonymousArrayOfByte, String paramAnonymousString)
        {
          try
          {
            return EMChatManager.this.cryptoUtils.encrypt(paramAnonymousArrayOfByte);
          }
          catch (Exception localException)
          {
            localException.printStackTrace();
          }
          return paramAnonymousArrayOfByte;
        }

        public byte[] decrypt(byte[] paramAnonymousArrayOfByte, String paramAnonymousString)
        {
          try
          {
            return EMChatManager.this.cryptoUtils.decrypt(paramAnonymousArrayOfByte);
          }
          catch (Exception localException)
          {
            localException.printStackTrace();
          }
          return paramAnonymousArrayOfByte;
        }
      };
    }
    return this.encryptProvider;
  }

  public void addVoiceCallStateChangeListener(EMCallStateChangeListener paramEMCallStateChangeListener)
  {
    EMVoiceCallManager.getInstance().addStateChangeListener(paramEMCallStateChangeListener);
  }

  public void addCallStateChangeListener(EMCallStateChangeListener paramEMCallStateChangeListener)
  {
    EMVoiceCallManager.getInstance().addStateChangeListener(paramEMCallStateChangeListener);
  }

  public void removeCallStateChangeListener(EMCallStateChangeListener paramEMCallStateChangeListener)
  {
    EMVoiceCallManager.getInstance().removeStateChangeListener(paramEMCallStateChangeListener);
  }

  public void makeVoiceCall(String paramString)
    throws EMServiceNotReadyException
  {
    EMVoiceCallManager.getInstance().makeVoiceCall(paramString);
  }

  public void answerCall()
    throws EMNoActiveCallException, EMNetworkUnconnectedException
  {
    EMVoiceCallManager.getInstance().answerCall();
  }

  public void rejectCall()
    throws EMNoActiveCallException
  {
    EMVoiceCallManager.getInstance().rejectCall();
  }

  public void endCall()
  {
    EMVoiceCallManager.getInstance().endCall();
  }

  public void makeVideoCall(String paramString)
    throws EMServiceNotReadyException
  {
    EMVoiceCallManager.getInstance().makeVideoCall(paramString);
  }

  CryptoUtils getCryptoUtils()
  {
    return this.cryptoUtils;
  }

  void doStartService()
  {
    EMLog.d("chat", "do start service: context:" + this.applicationContext);
    this.stopService = false;
    Intent localIntent = new Intent(this.applicationContext, EMChatService.class);
    this.applicationContext.startService(localIntent);
  }

  void doStopService()
  {
    try
    {
      if (this.applicationContext == null)
      {
        EMLog.w("chat", "applicationContext is null, the server is not started before");
        return;
      }
      EMLog.d("chat", "do stop service");
      this.stopService = true;
      Intent localIntent = new Intent(this.applicationContext, EMChatService.class);
      this.applicationContext.stopService(localIntent);
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
  }

  public void onReconnectionSuccessful()
  {
    this.handler.post(new Runnable()
    {
      public void run()
      {
        Iterator localIterator = EMChatManager.this.connectionListeners.iterator();
        while (localIterator.hasNext())
        {
          ConnectionListener localConnectionListener = (ConnectionListener)localIterator.next();
          if (localConnectionListener != null)
            localConnectionListener.onReConnected();
        }
      }
    });
    this.threadPool.submit(new Runnable()
    {
      public void run()
      {
        Iterator localIterator = EMChatManager.this.newConnectionListeners.iterator();
        while (localIterator.hasNext())
        {
          EMConnectionListener localEMConnectionListener = (EMConnectionListener)localIterator.next();
          localEMConnectionListener.onConnected();
        }
      }
    });
  }

  public void asyncFetchMessage(EMMessage paramEMMessage)
  {
    EMMessageHandler.getInstance().asyncFetchMessage(paramEMMessage);
  }

  public String importMessage(EMMessage paramEMMessage, boolean paramBoolean)
  {
    e.a().c(paramEMMessage);
    if (paramBoolean)
    {
      addMessage(paramEMMessage);
      notifyMessage(paramEMMessage);
    }
    return paramEMMessage.getMsgId();
  }

  public synchronized void importMessages(List<EMMessage> paramList)
  {
    e.a().a(paramList);
  }

  public boolean updateCurrentUserNick(String paramString)
  {
    if (TextUtils.isEmpty(paramString))
    {
      EMLog.e("chat", "nick name is null or empty");
      return false;
    }
    String str1 = getCurrentUser();
    if (TextUtils.isEmpty(str1))
    {
      EMLog.e("chat", "currentUser is null or empty");
      return false;
    }
    String str2 = getAccessToken();
    if (TextUtils.isEmpty(str2))
    {
      EMLog.e("chat", "token is null or empty");
      return false;
    }
    String str3 = HttpClientConfig.getBaseUrlByAppKey();
    StringBuilder localStringBuilder = new StringBuilder(str3);
    localStringBuilder.append("/");
    localStringBuilder.append("users/");
    localStringBuilder.append(str1);
    HashMap localHashMap = new HashMap();
    localHashMap.put("Authorization", "Bearer " + str2);
    JSONObject localJSONObject = new JSONObject();
    try
    {
      localJSONObject.put("nickname", paramString);
      String str4 = HttpClientManager.sendHttpRequest(localStringBuilder.toString(), localHashMap, localJSONObject.toString(), HttpClientManager.Method_PUT);
      if (str4.contains("error"))
      {
        EMLog.e("chat", "response error:" + str4);
        return false;
      }
    }
    catch (Exception localException)
    {
      EMLog.e("chat", "error:" + localException.getMessage());
      return false;
    }
    return true;
  }

  void initDB(String paramString)
  {
    Context localContext = EMChat.getInstance().getAppContext();
    if (localContext == null)
      return;
    EMChatDB.initDB(paramString);
  }

  void loadDB()
  {
    EMGroupManager.getInstance().clear();
    EMConversationManager.getInstance().clear();
    Thread local11 = new Thread()
    {
      public void run()
      {
        EMLog.d("chat", "");
        EMGroupManager.getInstance().loadAllGroups();
        EMChatManager.this.loadAllConversations();
      }
    };
    local11.setPriority(9);
    local11.start();
  }

  public String getAccessToken()
  {
    if (this.applicationContext == null)
    {
      EMLog.e("chat", "applicationContext is null");
      return null;
    }
    String str = EMChatConfig.getInstance().APPKEY;
    if (TextUtils.isEmpty(str))
    {
      EMLog.e("chat", "appkey is null or empty");
      return null;
    }
    try
    {
      return k.a().q();
    }
    catch (Exception localException)
    {
      EMLog.e("chat", "gettoken is error:" + localException.getMessage());
    }
    return null;
  }

  private void notifyMessageHandlerConnectionConnected()
  {
    EMMessageHandler.getInstance().onConnected();
  }

  public List<String> getConversationsUnread()
  {
    return EMConversationManager.getInstance().getConversationsUnread();
  }

  public boolean areAllConversationsLoaded()
  {
    return EMConversationManager.getInstance().areAllConversationsLoaded();
  }

  void forceReconnect()
  {
    EMSessionManager.getInstance().forceReconnect();
  }

  public boolean isSlientMessage(EMMessage paramEMMessage)
  {
    return paramEMMessage.getBooleanAttribute("em_ignore_notification", false);
  }

  private class ChatServiceConnection
    implements ServiceConnection
  {
    private ChatServiceConnection()
    {
    }

    public void onServiceConnected(ComponentName paramComponentName, IBinder paramIBinder)
    {
      ((EMChatService.LocalBinder)paramIBinder).getService();
      EMLog.d("chat", "service connected");
    }

    public void onServiceDisconnected(ComponentName paramComponentName)
    {
      EMLog.d("chat", "EaseMobService is disconnected");
      EMLog.d("chat", "service disconnected");
    }
  }

  private class EMChatManagerListener
    implements ChatManagerListener
  {
    private EMChatManagerListener()
    {
    }

    public void chatCreated(Chat paramChat, boolean paramBoolean)
    {
      String str = paramChat.getParticipant();
      EMLog.d("chat", "xmpp chat created for: " + str);
      EMChatManager.this.chats.put(str, paramChat);
    }
  }

  private class SingleInvitationListener
    implements PacketListener
  {
    private SingleInvitationListener()
    {
    }

    public void processPacket(Packet paramPacket)
    {
      if ((paramPacket instanceof Presence))
      {
        Presence localPresence = (Presence)paramPacket;
        if (EMChat.getInstance().appInited)
        {
          EMChatManager.this.processRosterPresence(localPresence);
        }
        else
        {
          EMLog.d("chat", "received roster presence, but app is not ready");
          EMChatManager.this.offlineRosterPresenceList.add(localPresence);
        }
      }
    }
  }

  private class XmppConnectionListener
    implements l
  {
    private XmppConnectionListener()
    {
    }

    public void connectionClosed()
    {
      EMLog.d("chat", "closing connection");
      EMChatManager.this.handler.post(new Runnable()
      {
        public void run()
        {
          Iterator localIterator = EMChatManager.this.connectionListeners.iterator();
          while (localIterator.hasNext())
          {
            ConnectionListener localConnectionListener = (ConnectionListener)localIterator.next();
            if (localConnectionListener != null)
              localConnectionListener.onDisConnected("connectionClosed");
          }
        }
      });
      EMChatManager.this.threadPool.submit(new Runnable()
      {
        public void run()
        {
          Iterator localIterator = EMChatManager.this.newConnectionListeners.iterator();
          while (localIterator.hasNext())
          {
            EMConnectionListener localEMConnectionListener = (EMConnectionListener)localIterator.next();
            localEMConnectionListener.onDisconnected(-1013);
          }
        }
      });
    }

    public void connectionClosedOnError(final Exception paramException)
    {
      EMLog.d("chat", "connectionClosedOnError");
      EMGroupManager.getInstance().removeMucs();
      EMChatManager.this.handler.post(new Runnable()
      {
        public void run()
        {
          Iterator localIterator = EMChatManager.this.connectionListeners.iterator();
          while (localIterator.hasNext())
          {
            ConnectionListener localConnectionListener = (ConnectionListener)localIterator.next();
            if (localConnectionListener != null)
              localConnectionListener.onDisConnected("connectionClosedOnError:" + paramException.getMessage());
          }
        }
      });
      EMChatManager.this.threadPool.submit(new Runnable()
      {
        public void run()
        {
          int i = -1013;
          if (paramException != null)
          {
            int j = EMExceptionUtils.fromExceptionToErrorCode(paramException);
            if (j != -999)
              i = j;
          }
          Iterator localIterator = EMChatManager.this.newConnectionListeners.iterator();
          while (localIterator.hasNext())
          {
            EMConnectionListener localEMConnectionListener = (EMConnectionListener)localIterator.next();
            try
            {
              localEMConnectionListener.onDisconnected(i);
            }
            catch (Exception localException)
            {
              localException.printStackTrace();
            }
          }
        }
      });
    }

    public void reconnectingIn(int paramInt)
    {
      EMLog.d("chat", "reconnectingIn in " + paramInt);
    }

    public void reconnectionFailed(final Exception paramException)
    {
      EMLog.d("chat", "reconnectionFailed");
      EMChatManager.this.handler.post(new Runnable()
      {
        public void run()
        {
          Iterator localIterator = EMChatManager.this.connectionListeners.iterator();
          while (localIterator.hasNext())
          {
            ConnectionListener localConnectionListener = (ConnectionListener)localIterator.next();
            if (localConnectionListener != null)
              localConnectionListener.onDisConnected(paramException.getMessage());
          }
        }
      });
      EMChatManager.this.threadPool.submit(new Runnable()
      {
        public void run()
        {
          int i = -1013;
          if (paramException != null)
          {
            int j = EMExceptionUtils.fromExceptionToErrorCode(paramException);
            if (j != -999)
              i = j;
          }
          Iterator localIterator = EMChatManager.this.newConnectionListeners.iterator();
          while (localIterator.hasNext())
          {
            EMConnectionListener localEMConnectionListener = (EMConnectionListener)localIterator.next();
            try
            {
              localEMConnectionListener.onDisconnected(i);
            }
            catch (Exception localException)
            {
              localException.printStackTrace();
            }
          }
        }
      });
    }

    public void reconnectionSuccessful()
    {
      EMLog.d("chat", "reconnectionSuccessful");
      EMSessionManager.getInstance().scheduleNextHeartBeat();
      EMChatManager.this.onReconnectionSuccessful();
    }

    public void onConnectionSuccessful()
    {
      EMLog.d("chat", "onConnectionSuccessful");
      EMChatManager.this.notifyMessageHandlerConnectionConnected();
      EMSessionManager.getInstance().scheduleNextHeartBeat();
      EMContactManager.getInstance().init(EMChat.getInstance().getAppContext(), EMChatManager.this.xmppConnectionManager);
      if (EMChatManager.this.xmppConnectionManager != null)
      {
        String str1 = EMSessionManager.getInstance().getLastLoginUser();
        String str2 = EMChatManager.this.xmppConnectionManager.getCurrentUser();
        if ((str2 != null) && ((str1 == null) || (!str1.equals(str2))))
        {
          EMSessionManager.getInstance().setLastLoginUser(str2);
          EMSessionManager.getInstance().setLastLoginPwd(EMChatManager.this.xmppConnectionManager.getCurrentPwd());
        }
      }
      EMChatManager.this.handler.post(new Runnable()
      {
        public void run()
        {
          Iterator localIterator = EMChatManager.this.connectionListeners.iterator();
          while (localIterator.hasNext())
          {
            ConnectionListener localConnectionListener = (ConnectionListener)localIterator.next();
            if (localConnectionListener != null)
              localConnectionListener.onConnected();
          }
        }
      });
      EMChatManager.this.threadPool.submit(new Runnable()
      {
        public void run()
        {
          Iterator localIterator = EMChatManager.this.newConnectionListeners.iterator();
          while (localIterator.hasNext())
          {
            EMConnectionListener localEMConnectionListener = (EMConnectionListener)localIterator.next();
            localEMConnectionListener.onConnected();
          }
        }
      });
    }

    public void onConnecting()
    {
      EMLog.d("chat", "onConnecting...");
    }
  }
}

/* Location:           D:\hygieia\userclient\common\libs\easemobchat_2.1.8.jar
 * Qualified Name:     com.easemob.chat.EMChatManager
 * JD-Core Version:    0.6.1
 */